package team.seekers.skill.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import team.seekers.skill.common.utils.SkillUtils;
import team.seekers.skill.entity.dao.Section;
import team.seekers.skill.entity.dao.Note;
import team.seekers.skill.entity.query.NoteQuery;
import team.seekers.skill.entity.vo.fore.list.NoteListVO;
import team.seekers.skill.mapper.NoteMapper;
import team.seekers.skill.service.SectionService;
import team.seekers.skill.service.NoteService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hbc
 * @since 2021-02-02
 */
@Service
public class NoteServiceImpl extends ServiceImpl<NoteMapper, Note> implements NoteService {

    @Autowired
    private SectionService sectionService;

    @Override
    public Note getNoteBySectionId(String sectionId) {
        QueryWrapper<Note> wrapper = new QueryWrapper<>();
        wrapper.eq("section_id",sectionId);
        Note note = getOne(wrapper);
        return note;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public boolean removeBySectionId(String sectionId){
        QueryWrapper<Note> wrapper = new QueryWrapper<>();
        wrapper.eq("section_id",sectionId);
        boolean remove = remove(wrapper);
        return remove;
    }

    @Override
    public Map<String, Object> pageNoteCondition(long current, long limit, NoteQuery noteQuery) {
        Page<Note> pageSkill = new Page<>(current,limit);
        QueryWrapper<Note> wrapper = new QueryWrapper<>();
        wrapper.eq("skill_id",noteQuery.getSkillId());
        page(pageSkill, wrapper);
        Long total = pageSkill.getTotal();
        List<Note> records = pageSkill.getRecords();
        if (records == null){
            return null;
        }
        List<NoteListVO> list = new ArrayList<>();
        for (Note record : records) {
            NoteListVO noteVO = new NoteListVO();
            BeanUtils.copyProperties(record,noteVO);
            if(record.getUserId().equals(SkillUtils.getUserId())){
                noteVO.setMe(true);
            }
            list.add(noteVO);
        }
        Map<String,Object> map = new HashMap<>();
        map.put("total",total);
        map.put("rows",list);
        return map;
    }
}
